import { Store } from '@/utils/storage'
import { RouteLocationNormalized, Router } from 'vue-router'

class Guard {
   private token: string
   constructor(private router: Router) {
      const storage = new Store()
      this.token = storage.getStorage('token')?.token
   }
   public run() {
      this.router.beforeEach((to, from) => {
         if (!this.checkIsLogin(to)) return { name: 'login' }
         if (this.checkIsGuest(to)) return from
      })
   }

   private checkIsLogin(route: RouteLocationNormalized): boolean {
      if (!route.meta.auth) return true
      if (!this.token) return false
      return true
   }

   private checkIsGuest(route: RouteLocationNormalized): boolean {
      if (route.meta.guest && !this.token) return false
      if (!route.meta.guest) return false
      return true
   }
}

export default (router: Router) => {
   new Guard(router).run()
}
